import * as utils from '../utils'
import { mat4, vec3 } from 'gl-matrix'

function createCourse18 (gl: WebGLRenderingContext) {
  gl.clearColor(0.0, 0.0, 0.0, 1.0)
  gl.clear(gl.COLOR_BUFFER_BIT)

  const vectexShaderSrc = `
  uniform mat4 u_ViewMatrix;
  attribute vec4 a_Position;
  attribute vec4 a_Color;
  varying vec4 v_Color;
    void main () {
        gl_Position = u_ViewMatrix * a_Position;
        v_Color = a_Color;
    }
  `

  const fragmentShaderSrc = `
  precision mediump float;
  varying vec4 v_Color;
    void main () {
        gl_FragColor = v_Color;
    }
  `
  const program = utils.initShaders(gl, vectexShaderSrc, fragmentShaderSrc)

  const vertics = new Float32Array([
    -0.2, -0.2, -0.2, 0.0, 0.0, 1.0, 1.0,
    +0.2, -0.2, -0.2, 0.0, 0.0, 1.0, 1.0,
    +0.0, +0.2, -0.2, 0.0, 0.0, 1.0, 1.0,

    -0.2, -0.2, 0.0, 0.0, 1.0, 0.0, 1.0,
    +0.2, -0.2, 0.0, 0.0, 1.0, 0.0, 1.0,
    +0.0, +0.2, 0.0, 0.0, 1.0, 0.0, 1.0,

    -0.2, -0.2, 0.2, 1.0, 0.0, 0.0, 1.0,
    +0.2, -0.2, 0.2, 1.0, 0.0, 0.0, 1.0,
    +0.0, +0.2, 0.2, 1.0, 0.0, 0.0, 1.0
  ])
  const size = vertics.BYTES_PER_ELEMENT
  const vectexBuffer = gl.createBuffer()
  gl.bindBuffer(gl.ARRAY_BUFFER, vectexBuffer)
  gl.bufferData(gl.ARRAY_BUFFER, vertics, gl.STATIC_DRAW)

  const aPosition = gl.getAttribLocation(program, 'a_Position')
  gl.vertexAttribPointer(aPosition, 3, gl.FLOAT, false, size * 7, 0)
  gl.enableVertexAttribArray(aPosition)

  const aColor = gl.getAttribLocation(program, 'a_Color')
  gl.vertexAttribPointer(aColor, 4, gl.FLOAT, false, size * 7, size * 3)
  gl.enableVertexAttribArray(aColor)

  const eye = vec3.create()
  vec3.set(eye, 0.20, 0.25, 0.25)
  const center = vec3.create()
  vec3.set(center, 0.0, 0.0, 0.0)
  const up = vec3.create()
  vec3.set(up, 0.0, 1.0, 0.0)
  const viewMatrix = mat4.create()
  mat4.lookAt(viewMatrix, eye, center, up)

  const uViewMatrix = gl.getUniformLocation(program, 'u_ViewMatrix')
  gl.uniformMatrix4fv(uViewMatrix, false, viewMatrix)

  gl.drawArrays(gl.TRIANGLES, 0, 9)

  const lines = new Float32Array([
    0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0,
    1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0,

    0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0,
    0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0,

    0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0,
    0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0
  ])

  const lineBuffer = gl.createBuffer()
  gl.bindBuffer(gl.ARRAY_BUFFER, lineBuffer)
  gl.bufferData(gl.ARRAY_BUFFER, lines, gl.STATIC_DRAW)

  const linePosition = gl.getAttribLocation(program, 'a_Position')
  gl.vertexAttribPointer(aPosition, 3, gl.FLOAT, false, size * 7, 0)
  gl.enableVertexAttribArray(linePosition)

  const lineColor = gl.getAttribLocation(program, 'a_Color')
  gl.vertexAttribPointer(aColor, 4, gl.FLOAT, false, size * 7, size * 3)
  gl.enableVertexAttribArray(lineColor)

  gl.drawArrays(gl.LINES, 0, 9)
}

export {
  createCourse18
}
